package org.luxor.commons.security.config.resource;

import org.luxor.commons.openfeign.config.DefaultFeignAutoConfiguration;
import org.luxor.commons.security.component.RestAccessDeniedHandler;
import org.luxor.commons.security.component.RestAuthExceptionEntryPoint;
import org.luxor.commons.security.component.RestBearerTokenExtractor;
import org.luxor.commons.security.component.RestUserAuthenticationConverter;
import org.luxor.commons.security.config.TokenRelayAutoConfiguration;
import org.luxor.commons.security.config.WebSecurityProperties;
import org.luxor.commons.security.constant.SecurityConstants;
import org.luxor.commons.security.utils.SecurityUtils;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * OAuth2 ResourceServer 配置适配器
 *
 * @author lengleng @date 2019/03/08
 *
 * <p>
 * 1. 支持remoteTokenServices 负载均衡
 * 2. 支持 获取用户全部信息
 * 3. 接口对外暴露，不校验 Authentication Header 头
 */
@Import({DefaultFeignAutoConfiguration.class, TokenRelayAutoConfiguration.class})
public class OAuth2ResourceServerConfigurer extends ResourceServerConfigurerAdapter {

    private final WebSecurityProperties webSecurityProperties;

    @Resource
    private ResourceServerProperties resourceProperties;
    @Resource
    private RemoteTokenServices remoteTokenServices;
    @Resource
    private RestTemplate lbRestTemplate;

    public OAuth2ResourceServerConfigurer(WebSecurityProperties webSecurityProperties) {
        Assert.notNull(webSecurityProperties, "Spring容器中找不到[webSecurityProperties]的实例化对象!");
        this.webSecurityProperties = webSecurityProperties;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
        UserAuthenticationConverter userTokenConverter = new RestUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userTokenConverter);

        remoteTokenServices.setRestTemplate(lbRestTemplate);
        remoteTokenServices.setAccessTokenConverter(accessTokenConverter);

        resources.resourceId(resourceProperties.getResourceId()).authenticationEntryPoint(new RestAuthExceptionEntryPoint())
                .tokenExtractor(new RestBearerTokenExtractor(webSecurityProperties))
                .accessDeniedHandler(new RestAccessDeniedHandler())
                .tokenServices(remoteTokenServices);
    }

    /**
     * 配置鉴权机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {

        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                .antMatchers(SecurityConstants.DEFAULT_ANON_URIS).permitAll()
                .antMatchers(webSecurityProperties.getAnonUris()).permitAll()
                .anyRequest().anonymous()
                .and().formLogin().disable().logout().disable()
                .anonymous().principal(SecurityUtils.ANONYMUS)
                .and().exceptionHandling()
                .authenticationEntryPoint(new RestAuthExceptionEntryPoint()).accessDeniedHandler(new RestAccessDeniedHandler())
                .and().csrf().disable();
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource(){
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }

}
